<template>
  <div class="pull-refresh-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :offset="10"
        @load="onLoad"
      >
        <slot />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
export default {
  name: 'PullRefreshList',
  props: {
    total: {
      type: Number,
      default: 0
    },
    pageNo: {
      type: Number,
      default: 0
    },
    limit: {
      type: Number,
      default: 0
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      finished: false,
      refreshing: false
    }
  },
  methods: {
    onLoad() {
      if (this.refreshing) {
        // 下拉刷新事清空数组重置页数
        this.$emit('update:data', [])
        this.$emit('update:pageNo', 1)
        this.refreshing = false
      }
      this.$emit('getList', res => {
        this.$nextTick(() => {
          this.loading = false
          // 连接加载的数据
          this.$emit('update:data', this.data.concat(res))
          // const product = this.pageNo * this.limit
          // 请求的数据长度少于每页请求最大数 结束加载
          if (res.length < this.limit) {
            this.finished = true
          } else {
            this.$emit('update:pageNo', this.pageNo + 1)
          }
        })
      })
    },
    onRefresh() {
      // 手动下拉刷新
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.$nextTick(() => {
        this.onLoad()
      })
    },
    onSearch() {
      // 触发拉下刷新功能
      this.refreshing = true
      this.onRefresh()
    }
  }
}
</script>
